package com.example.demo.common;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect //定义切面
@Component
public class UserAspect {

    //切点
    @Pointcut("execution(* com.example.demo.controller.UserController.*(..))")
    public void pointcut(){

    }

    //前置通知
    @Before("pointcut()")
    public void doBefore(){
        System.out.println("执行了前置通知");
    }

    //后置通知
    @After("pointcut()")
    public void doAfter(){
        System.out.println("执行了后置通知");
    }

    //执行return之前通知
    @AfterReturning("pointcut()")
    public void doAfterReturning(){
        System.out.println("执行return之前通知");
    }

    //抛出异常之前通知
    @AfterThrowing("pointcut()")
    public void doAfterThrowing(){
        System.out.println("执行抛出异常之前通知");
    }

    //环绕通知
    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知执行之前");
        //开始计算时间
        StopWatch stopWatch=new StopWatch("计时器");
        stopWatch.start();
        //执行目标方法
        Object result=joinPoint.proceed();
        stopWatch.stop();
        System.out.println("执行时间："+stopWatch.getTotalTimeMillis()+"s");
        System.out.println("环绕通知执行之后");
        return result;
    }
}
